﻿using System;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;

namespace Cybozu.SharePoint.CategoryFilter
{
    public class CategoryFilterSettingsPage : LayoutsPageBase
    {
        protected HtmlAnchor TitleBreadcrumbListEdit;

        protected RadioButtonList UseCategoryFilter;
        protected DropDownList CategoryField;
        protected ButtonSection Buttons;
        protected Button Save;
        protected HtmlInputButton Cancel;

        protected SPField PrevCategoryField = null;

        public const string DefaultViewSetupPath = "pages\\viewpage.aspx";
        public const string CategoryFilterViewSetupPath = "pages\\Cybozu\\SPListKit\\CategoryFilterView.aspx";

        public const string AsCategory = "AsCategory";

        protected override SPBasePermissions RightsRequired
        {
            get
            {
                return SPBasePermissions.ManageLists;
            }
        }

        protected void Page_Init()
        {
            SPList splist = SPContext.Current.List;
            SPWeb web = SPContext.Current.Web;

            string listEditUrl = Utility.GetServerRelativeListEditUrl(splist);

            // breadcrumbs
            TitleBreadcrumbListEdit.HRef = listEditUrl;

            // UserFilterByCategory
            UseCategoryFilter.RepeatDirection = RepeatDirection.Horizontal;
            UseCategoryFilter.Items.Add(new ListItem(Utility.GetLocalizedString(Resource.fld_yes, Resource.core, web), bool.TrueString));
            UseCategoryFilter.Items.Add(new ListItem(Utility.GetLocalizedString(Resource.fld_no, Resource.core, web), bool.FalseString));

            // CategoryField
            foreach (SPField field in splist.Fields)
            {
                if (field.Hidden) continue;

                if (field.Type == SPFieldType.Choice ||
                    field.Type == SPFieldType.MultiChoice ||
                    field.Type == SPFieldType.Lookup)
                {
                    if (SPBuiltInFieldId.Contains(field.Id)) continue;

                    CategoryField.Items.Add(new ListItem(field.Title, field.InternalName));

                    string asCategory = Utility.GetFieldAttribute(field, AsCategory) as string;
                    if (asCategory == "1")
                    {
                        PrevCategoryField = field;
                    }
                }
            }

            if (!IsPostBack)
            {
                if (PrevCategoryField != null)
                {
                    CategoryField.SelectedValue = PrevCategoryField.InternalName;
                }

                if (CategoryField.Items.Count == 0)
                {
                    UseCategoryFilter.SelectedValue = bool.FalseString;
                    UseCategoryFilter.Enabled = false;
                }
                else
                {
                    string viewSetupPath = GetViewSetupPath();
                    if (string.Compare(viewSetupPath, DefaultViewSetupPath, true) == 0)
                    {
                        UseCategoryFilter.SelectedValue = bool.FalseString;
                    }
                    else if (string.Compare(viewSetupPath, CategoryFilterViewSetupPath, true) == 0)
                    {
                        UseCategoryFilter.SelectedValue = bool.TrueString;
                    }
                    else
                    {
                        UseCategoryFilter.SelectedValue = bool.FalseString;
                        UseCategoryFilter.Enabled = false;
                        Save.Enabled = false;
                    }
                }
            }

            // Buttons
            Buttons.ShowStandardCancelButton = false;

            // Save
            if (Save.Enabled)
            {
                Save.Click += new EventHandler(Save_Click);
            }

            // Cancel
            Cancel.Attributes["onclick"] = string.Format("window.location.href='{0}'", listEditUrl);
        }

        void Save_Click(object sender, EventArgs e)
        {
            SPList splist = SPContext.Current.List;

            if (PrevCategoryField != null)
            {
                if (PrevCategoryField.InternalName != CategoryField.SelectedValue)
                {
                    Utility.SetFieldAttribute(PrevCategoryField, AsCategory, string.Empty);
                    PrevCategoryField.Update();

                    if (!string.IsNullOrEmpty(CategoryField.SelectedValue))
                    {
                        SPField categoryField = splist.Fields.GetFieldByInternalName(CategoryField.SelectedValue);
                        Utility.SetFieldAttribute(categoryField, AsCategory, "1");
                        categoryField.Update();
                    }
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(CategoryField.SelectedValue))
                {
                    SPField categoryField = splist.Fields.GetFieldByInternalName(CategoryField.SelectedValue);
                    Utility.SetFieldAttribute(categoryField, AsCategory, "1");
                    categoryField.Update();
                }
            }

            string viewSetupPath = GetViewSetupPath();
            if (UseCategoryFilter.SelectedValue == bool.TrueString)
            {
                if (string.Compare(viewSetupPath, CategoryFilterViewSetupPath, true) != 0)
                {
                    SetViewSetupPath(true);
                }
            }
            else if (UseCategoryFilter.SelectedValue == bool.FalseString)
            {
                if (string.Compare(viewSetupPath, DefaultViewSetupPath, true) != 0)
                {
                    SetViewSetupPath(false);
                }
            }

            SPUtility.Redirect(Utility.GetServerRelativeListEditUrl(splist), SPRedirectFlags.Default, HttpContext.Current);
        }

        public static SPField GetCategoryField(SPList splist)
        {
            foreach (SPField field in splist.Fields)
            {
                if (field.Hidden) continue;

                if (field.Type == SPFieldType.Choice ||
                    field.Type == SPFieldType.MultiChoice ||
                    field.Type == SPFieldType.Lookup)
                {
                    string asCategory = Utility.GetFieldAttribute(field, AsCategory) as string;
                    if (asCategory == "1") return field;
                }
            }

            return null;
        }

        protected string GetViewSetupPath()
        {
            SPList splist = SPContext.Current.List;

            string viewSetupPath = string.Empty;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                string connectionString = SPContext.Current.Site.ContentDatabase.DatabaseConnectionString;

                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    SqlCommand cmd = conn.CreateCommand();
                    cmd.CommandText = @"SELECT SetupPath FROM AllDocs WHERE LeafName=@ViewName AND ListId=@ListId";
                    cmd.Parameters.Add("@ViewName", SqlDbType.NVarChar, 128).Value = SPUtility.GetUrlFileName(splist.DefaultViewUrl);
                    cmd.Parameters.Add("@ListId", SqlDbType.UniqueIdentifier).Value = splist.ID;

                    conn.Open();

                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        viewSetupPath = reader["SetupPath"].ToString();
                    }
                    reader.Close();

                    cmd.Dispose();
                }
            });

            return viewSetupPath;
        }

        protected void SetViewSetupPath(bool categorize)
        {
            SPList splist = SPContext.Current.List;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                string connectionString = SPContext.Current.Site.ContentDatabase.DatabaseConnectionString;

                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    SqlCommand cmd = conn.CreateCommand();
                    cmd.CommandText = @"UPDATE AllDocs SET SetupPath=@SetupPath WHERE LeafName=@ViewName AND ListId=@ListId";
                    cmd.Parameters.Add("@SetupPath", SqlDbType.VarChar, 255).Value = categorize ? CategoryFilterViewSetupPath : DefaultViewSetupPath;
                    cmd.Parameters.Add("@ViewName", SqlDbType.NVarChar, 128).Value = SPUtility.GetUrlFileName(splist.DefaultViewUrl);
                    cmd.Parameters.Add("@ListId", SqlDbType.UniqueIdentifier).Value = splist.ID;

                    conn.Open();

                    cmd.ExecuteNonQuery();
                    cmd.Dispose();
                }
            });
        }
    }
}
